using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Logging;

namespace SeataNet.Core.Serialization
{
    /// <summary>
    /// 序列化服务扩展
    /// </summary>
    public static class SerializationServiceExtensions
    {
        /// <summary>
        /// 添加序列化服务（默认JSON）
        /// </summary>
        public static IServiceCollection AddSerialization(this IServiceCollection services)
        {
            return services.AddSerialization(SerializerType.Json);
        }

        /// <summary>
        /// 添加序列化服务
        /// </summary>
        public static IServiceCollection AddSerialization(this IServiceCollection services, SerializerType defaultType)
        {
            // 注册序列化器工厂
            services.TryAddSingleton<ISerializerFactory>(sp =>
            {
                var loggerFactory = sp.GetRequiredService<ILoggerFactory>();
                var logger = loggerFactory.CreateLogger<DefaultSerializerFactory>();
                return new DefaultSerializerFactory(logger, loggerFactory, defaultType);
            });

            // 注册默认序列化器
            services.TryAddSingleton<ISerializer>(sp =>
            {
                var factory = sp.GetRequiredService<ISerializerFactory>();
                return factory.GetDefaultSerializer();
            });

            return services;
        }

        /// <summary>
        /// 添加JSON序列化器
        /// </summary>
        public static IServiceCollection AddJsonSerializer(this IServiceCollection services)
        {
            services.TryAddSingleton<ISerializer>(sp =>
            {
                var loggerFactory = sp.GetRequiredService<ILoggerFactory>();
                return new JsonSerializer(loggerFactory.CreateLogger<JsonSerializer>());
            });

            return services;
        }

        /// <summary>
        /// 添加Protobuf序列化器
        /// </summary>
        public static IServiceCollection AddProtobufSerializer(this IServiceCollection services)
        {
            services.TryAddSingleton<ISerializer>(sp =>
            {
                var loggerFactory = sp.GetRequiredService<ILoggerFactory>();
                return new ProtobufSerializer(loggerFactory.CreateLogger<ProtobufSerializer>());
            });

            return services;
        }

        /// <summary>
        /// 添加MessagePack序列化器
        /// </summary>
        public static IServiceCollection AddMessagePackSerializer(this IServiceCollection services)
        {
            services.TryAddSingleton<ISerializer>(sp =>
            {
                var loggerFactory = sp.GetRequiredService<ILoggerFactory>();
                return new MessagePackSerializer(loggerFactory.CreateLogger<MessagePackSerializer>());
            });

            return services;
        }
    }
}
